package lv.dysnomia.songs.util

import scala.xml.XML

object PropertyWriter {

  val languages = Array("de","en","lt","ltg","lv")
  val hex = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')

  def main(args: Array[String]): Unit = {
    if (args.length < 1) {
      println("Usage: scala lv.dysnomia.songs.util.PropertyWriter workingdir")
      System.exit(0)
    }
    for (lang <- languages) {
      val propertyFile = XML.loadFile(args(0) + "/messages_" + lang + ".xml")
      val out = new java.io.FileWriter(args(0) + "/messages_" + lang + ".properties")
      out.write("# Generated file, do not edit.\n")
      out.write("# Created by PropertyWriter from an XML file " + args(0) + "\n")
      for (b <- propertyFile \\ "entry") {
    	out.write(b \ "@key" + "=" + unicodeEscape(b.text) + "\n")
      }
      out.close
    }
  }

  /**
   * TODO Publish as func.prog. sample
   */
  def unicodeEscape(s: String): String = {
    val ll: List[List[Char]] = s.toList.map(c =>
      if ((c >> 7) > 0) {
        List('\\', 'u', hex((c >> 12) & 0xF), hex((c >> 8) & 0xF), hex((c >> 4) & 0xF), hex(c & 0xF))
      } else {
        List(c)
      })
    ll.flatten.mkString("")
  }
}